//总宽度可以改为求总最大值减去总最小值
//f[i]为0~(i-1)中小于nums[i]的数量
//g[i]为(i+1)~(len-1)中大于等于nums[i]的数量(考虑到相同的数会有重复)
//总最大值为sigema(nums[i]*2^f[i]*2^g[i])
//总最小值类似
import java.util.Arrays;

public class Solution891 {

    static class BitTree{
        int n;
        int[] h;

        public BitTree(int n){
            this.n=n;
            h=new int[n+1];
        }

        public void update(int x,int d){
            while (x<=n){
                h[x]+=d;
                x+=lowbit(x);
            }
        }

        private int lowbit(int x) {
            return x&(-x);
        }

        public int query(int x){
            int t=0;
            while (x>0){
                t+=h[x];
                x-=lowbit(x);
            }
            return t;
        }
    }

    public int sumSubseqWidths(int[] nums) {
        long mod=1000000007;
        int m= Arrays.stream(nums).max().getAsInt();
        BitTree bitTree=new BitTree(m);
        int[] f=new int[nums.length];
        for (int i=0;i<nums.length;i++){
            f[i]=bitTree.query(nums[i]-1);
            bitTree.update(nums[i],1);
        }
        bitTree=new BitTree(m);
        int[] g=new int[nums.length];
        for (int i=nums.length-1;i>=0;i--){
            g[i]=bitTree.query(nums[i]);
            bitTree.update(nums[i],1);
        }
        long[] mul=new long[nums.length];
        mul[0]=1;
        for (int i=1;i<nums.length;i++){
            mul[i]=mul[i-1]*2%mod;
        }
        long ans1=0;
        for (int i=0;i<nums.length;i++){
            ans1=(ans1+mul[f[i]]*mul[g[i]]%mod*nums[i]%mod)%mod;
        }
        long ans2=0;
        for (int i=0;i<nums.length;i++){
            ans2=(ans2+mul[i-f[i]]*mul[nums.length-i-1-g[i]]%mod*nums[i]%mod)%mod;
        }
        return (int)((ans1-ans2+mod)%mod);
    }

    public static void main(String[] args) {
        System.out.println(new Solution891().sumSubseqWidths(new int[]{2,1,3}));
    }
}
